package com.itheima.reggie.controller;

import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import com.itheima.reggie.config.MyConfig;
import com.itheima.reggie.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/wx")
public class WxPayController {
    @Autowired
    private OrdersService ordersService;
    @PostMapping("/notify")
    public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {
        System.out.println("我收到回调信息");
        String string = convertToString(request.getInputStream());//支付成功后收到微信回调信息转为xml字符串
        Map<String, String> map = WXPayUtil.xmlToMap(string);
        String result_code = map.get("result_code");
        if ("SUCCESS".equals(result_code)) {
            //微信流水号 记录微信的支付凭证
            String transaction_id = map.get("transaction_id");
            //商家订单号查询订单是否支付成功
            String out_trade_no = map.get("out_trade_no");
            boolean flag = checkOrdersStates(out_trade_no);
            if (flag){
                ordersService.updateState(out_trade_no,transaction_id);
            }
        }

        response.setContentType("text/xml");
        String data = " <xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
        response.getWriter().write(data);
    }

    private boolean checkOrdersStates(String out_trade_no) throws Exception {

        MyConfig config = new MyConfig();
        WXPay wxpay = new WXPay(config);

        Map<String, String> data = new HashMap<String, String>();
        data.put("out_trade_no", out_trade_no);
        Map<String, String> resp = wxpay.orderQuery(data);
        String trade_state = resp.get("trade_state");
        return "SUCCESS".equals(trade_state);
    }

    /**
     * 输入流转换为xml字符串
     *
     * @param inputStream
     * @return
     */
    public static String convertToString(InputStream inputStream) throws
            IOException {
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inputStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        outSteam.close();
        inputStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");
        return result;
    }
}
